package jdk8.optional;

import java.util.Optional;

public class OptionlTest {

    public static void main(String[] args) {
        // Person person = new Person();
        Person person = null;
        OptionlTest optionlTest = new OptionlTest();

        System.out.println("getCity3 = [" + optionlTest.getCity3(person) + "]");
        System.out.println("getCityUsingOptional = [" + optionlTest.getCityUsingOptional(person) + "]");

    }

    /**
     * 理想的方法
     * @return
     */
    public String getCity(Person person) {
        String city = person.getHouse().getAddress().getCity();
        return city;
    }


    /**
     * 实际中的方法
     * @param person
     * @return
     */
    public String getCity2(Person person) {
        if (person != null) {
            House house = person.getHouse();
            if (house != null) {
                Address address = house.getAddress();
                if (address != null) {
                    String city = address.getCity();
                    return city;
                }
            }
        }
        return "unknown";
    }

    /**
     * 实际中的优化了if结构的方法
     * @param person
     * @return
     */
    public String getCity3(Person person) {
        String city = "unknown";
        if (person == null) {
            return city;
        }

        House house = person.getHouse();
        if (house == null) {
            return city;
        }

        Address address = house.getAddress();
        if (address == null) {
            return city;
        }

        return address.getCity();
    }

    /**
     * 用optional改造的方法
     * @param person
     * @return
     */
    public String getCityUsingOptional(Person person) {
        String city = Optional.ofNullable(person)
                .map(Person::getHouse)
                .map(House::getAddress)
                .map(Address::getCity).orElse("Unknown city");
        return city;
    }

}
